/**
 * OptimizationManager - 性能优化管理器
 * 根据设备性能自动调整渲染策略
 */

import { OPTIMIZATION_STRATEGIES } from './config.js'

class OptimizationManager {
  constructor() {
    this.currentStrategy = 'normal'
    this.deviceInfo = null
    this.performanceLevel = 'high' // high, medium, low, critical
    this.optimizations = {
      simplifyGradients: false,
      disableShadows: false,
      reduceAnimationComplexity: false,
      disableNonEssentialAnimations: false
    }
    
    this.detectDevice()
  }

  /**
   * 检测设备性能
   */
  detectDevice() {
    try {
      this.deviceInfo = uni.getSystemInfoSync()
      
      // 根据设备信息评估性能等级
      this.evaluatePerformanceLevel()
      
      console.log('Device detected:', {
        platform: this.deviceInfo.platform,
        model: this.deviceInfo.model,
        performanceLevel: this.performanceLevel
      })
    } catch (error) {
      console.error('Failed to detect device:', error)
      this.performanceLevel = 'medium'
    }
  }

  /**
   * 评估性能等级
   */
  evaluatePerformanceLevel() {
    if (!this.deviceInfo) {
      this.performanceLevel = 'medium'
      return
    }
    
    const { platform, model, system } = this.deviceInfo
    
    // iOS设备通常性能较好
    if (platform === 'ios') {
      // iPhone 8及以上为高性能
      if (model && (model.includes('iPhone') && !model.includes('iPhone 6') && !model.includes('iPhone 7'))) {
        this.performanceLevel = 'high'
      } else {
        this.performanceLevel = 'medium'
      }
    }
    // Android设备根据系统版本判断
    else if (platform === 'android') {
      const androidVersion = parseInt(system.match(/\d+/)?.[0] || '0')
      
      if (androidVersion >= 10) {
        this.performanceLevel = 'high'
      } else if (androidVersion >= 8) {
        this.performanceLevel = 'medium'
      } else {
        this.performanceLevel = 'low'
      }
    }
    // PC端默认高性能
    else if (platform === 'windows' || platform === 'mac') {
      this.performanceLevel = 'high'
    }
    // 其他设备默认中等性能
    else {
      this.performanceLevel = 'medium'
    }
  }

  /**
   * 应用优化策略
   */
  applyStrategy(strategyName) {
    const strategy = OPTIMIZATION_STRATEGIES[strategyName]
    
    if (!strategy) {
      console.warn('Unknown optimization strategy:', strategyName)
      return
    }
    
    this.currentStrategy = strategyName
    
    // 更新优化选项
    this.optimizations = {
      simplifyGradients: strategy.simplifyGradients || false,
      disableShadows: strategy.disableShadows || false,
      reduceAnimationComplexity: strategy.reduceAnimationComplexity || false,
      disableNonEssentialAnimations: strategy.disableNonEssentialAnimations || false
    }
    
    console.log('Applied optimization strategy:', strategyName, this.optimizations)
    
    return {
      targetFPS: strategy.targetFPS,
      optimizations: this.optimizations
    }
  }

  /**
   * 根据FPS自动调整策略
   */
  autoAdjustStrategy(currentFPS) {
    let newStrategy = null
    
    if (currentFPS < 15) {
      // 严重性能问题
      if (this.currentStrategy !== 'criticalPerformance') {
        newStrategy = 'criticalPerformance'
        this.performanceLevel = 'critical'
      }
    } else if (currentFPS < 30) {
      // 低性能
      if (this.currentStrategy !== 'lowPerformance' && this.currentStrategy !== 'criticalPerformance') {
        newStrategy = 'lowPerformance'
        this.performanceLevel = 'low'
      }
    } else if (currentFPS >= 50) {
      // 性能恢复
      if (this.currentStrategy !== 'normal' && this.performanceLevel !== 'high') {
        newStrategy = 'normal'
        this.performanceLevel = 'medium'
      }
    }
    
    if (newStrategy) {
      console.log('Auto-adjusting strategy from', this.currentStrategy, 'to', newStrategy)
      return this.applyStrategy(newStrategy)
    }
    
    return null
  }

  /**
   * 获取当前优化选项
   */
  getOptimizations() {
    return this.optimizations
  }

  /**
   * 获取性能等级
   */
  getPerformanceLevel() {
    return this.performanceLevel
  }

  /**
   * 获取当前策略
   */
  getCurrentStrategy() {
    return this.currentStrategy
  }

  /**
   * 是否应该简化渐变
   */
  shouldSimplifyGradients() {
    return this.optimizations.simplifyGradients
  }

  /**
   * 是否应该禁用阴影
   */
  shouldDisableShadows() {
    return this.optimizations.disableShadows
  }

  /**
   * 是否应该减少动画复杂度
   */
  shouldReduceAnimationComplexity() {
    return this.optimizations.reduceAnimationComplexity
  }

  /**
   * 是否应该禁用非必要动画
   */
  shouldDisableNonEssentialAnimations() {
    return this.optimizations.disableNonEssentialAnimations
  }

  /**
   * 获取推荐的目标FPS
   */
  getRecommendedFPS() {
    switch (this.performanceLevel) {
      case 'high':
        return 60
      case 'medium':
        return 45
      case 'low':
        return 30
      case 'critical':
        return 15
      default:
        return 60
    }
  }

  /**
   * 重置优化
   */
  reset() {
    this.currentStrategy = 'normal'
    this.optimizations = {
      simplifyGradients: false,
      disableShadows: false,
      reduceAnimationComplexity: false,
      disableNonEssentialAnimations: false
    }
    this.evaluatePerformanceLevel()
  }
}

export default OptimizationManager
